package com.fuyun.rpc.registry.zk;

import cn.hutool.core.util.StrUtil;
import com.fuyun.rpc.constant.RpcConstant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.List;

/**
 * @Author fuyun。
 * @Date 2025/8/22 11:01。
 * @Description: TODO。
 **/

@Slf4j
public class ZkCLient {

    private static final int maxRetries = 3;
    private static final int baseSleepTimeMs = 1000;


    private CuratorFramework client;

    public ZkCLient() {
        this(RpcConstant.ZK_IP, RpcConstant.ZK_PORT);

    }

    public ZkCLient(String host, int port) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);

        client = CuratorFrameworkFactory.builder()
                .connectString(host + StrUtil.COLON + port)
                .retryPolicy(retryPolicy)
                .build();
        log.info("开始连接zk");
        client.start();
        log.info("zk链接成功");
    }

    @SneakyThrows
    public void createPersistentNode(String path) {
        if(StrUtil.isBlank(path)) {
            throw new IllegalArgumentException("path is blank");
        }
        if (client.checkExists().forPath(path) != null) {
            log.info("该节点已存在");
            return;
        }
        log.info("创建节点");
        client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path);
    }

    @SneakyThrows
    public List<String> getChildrenNode(String path) {
        if(StrUtil.isBlank(path)) {
            throw new IllegalArgumentException("path is blank");
        }
        return client.getChildren().forPath(path);
    }

}
